#!/bin/bash

show_help() {
        echo -e "TianNi OpenStack Tool"
        echo -e "Usage:\n\t$0 <sub-command> [options...] [parameters...]"
        echo -e "Commands:"
        echo -e "\tregistry                \tdocker private registry for openstack"
        echo -e "\tssh                     \tset up ssh trust among hosts"
        echo -e "\tinstall                 \tinstall openstack (kolla)"
        echo -e "\tdestroy                 \tuninstall openstack (kolla)"
        echo -e "\tmariadb_backup          \tmariadb backup (kolla)"
        echo -e "\tmariadb_recovery        \tmariadb recovery (kolla)"
        echo -e "\ttest                    \ttest kolla"
        echo -e "Options:"
        echo -e "\t--help, -h              \tshow this help."
        echo -e "Example:"
        echo -e "\tINVENTORY=all-in-one tnc-openstack destroy -- -- --yes-i-really-really-mean-it"
        echo -e "\ttnc-openstack mariadb_backup --skip-install-kolla --confdir work/144_50 -- --full"
}

# add '.' to PATH 
set_current_path() {
    local found=false
    local savedifs=$IFS
    local x=
    local dest=$(dirname $1)

    IFS=$':'; for x in $PATH; do
        if [ "$x" == "." ]; then
            found=true
            break
        fi
    done
    IFS=$savedifs

    if $found; then
        return 0
    fi

    PATH=$dest:$PATH
    export PATH
    return 0
}

[ -z "$KOLLADIR" ] && { echo "source tn-openstack-var"; . tn-openstack-var; }

cmdopts=$(getopt --longoptions help \
                     --options +h -- "$@")
if [ $? -ne 0 ] ; then
  echo "Terminating..." 1>&2
  exit 1
fi

# set positional parameters
eval set -- "$cmdopts"

[ $# -eq 1 ] && { show_help; exit 0; }

while true; do
  case "$1" in
    -h | --help )
        show_help
        exit ;;
    -- ) shift; break ;;
    * ) break ;;
  esac
done

set_current_path $0

while true; do
  case "$1" in
    registry )
        shift
        exec kollatest -t "$0 registry" $@
        exit $? ;;
    ssh )
        shift
        exec tnc-ssh-hosts.sh -t "$0 ssh" $@
        exit $? ;;
    install )
        shift
        exec call-kolla-install.sh -t "$0 install" $@
        exit $? ;;
    destroy )
        shift
        # swap options and parameter 'destroy'
        exec call-kolla-uninstall.sh -t "$0 destroy [options...|--] [-- kolla-ansible_options]" $@ 
        exit $? ;;
    mariadb_backup )
        shift
        exec call-kolla-mariadb.sh -t "$0 mariadb_backup [options...|--] [-- kolla-ansible_options]" --action backup $@
        exit $? ;;
    mariadb_recovery )
        shift
        exec call-kolla-mariadb-recovery.sh -t "$0 mariadb_recovery [options...|--] [-- kolla-ansible_options]" $@ 
        exit $? ;;
    test )
        shift
        exec call-kolla-test.sh -t "$0 test" $@
        exit $? ;;
    -- ) shift; break ;;
    * )
        echo "error input" 1>&2
        break ;;
  esac
done
